package com.github.caijh.mall.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.Random;
import javax.imageio.ImageIO;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.druid.util.Base64;
import com.github.caijh.commons.util.RandomUtils;

public class ValidateCodeUtil {

    //验证码类，用于最后返回此对象，包含验证码图片base64和真值
    private static final Random random = new Random();              //随机类，用于生成随机参数

    private static final int WIDTH = 80;     //图片宽度
    private static final int HEIGHT = 34;    //图片高度
    private static final int STRING_NUM = 4;  //字符的数量
    private static final int LINE_SIZE = 20;  //干扰线数量

    private ValidateCodeUtil() {
        super();
    }

    /**
     * 获得颜色
     * @param frontColor 覆盖颜色
     * @param backColor 背景色
     * @author Mr.Zhang
     * @since 2020-04-16
     * @return Color
     */
    private static Color getRandColor(int frontColor, int backColor) {
        if(frontColor > 255)
            frontColor = 255;
        if(backColor > 255)
            backColor = 255;

        int red = frontColor + random.nextInt(backColor - frontColor - 16);
        int green = frontColor + random.nextInt(backColor - frontColor -14);
        int blue = frontColor + random.nextInt(backColor - frontColor -18);
        return new Color(red, green, blue);
    }

    private static void drawString(Graphics graphics, int i, String randChar) {
        Graphics2D g2d = (Graphics2D) graphics;
        g2d.setFont(new Font("Fixedsys", Font.BOLD, 25));   //设置字体
        g2d.setColor(new Color(random.nextFloat(), random.nextFloat(), random.nextFloat()));//设置颜色
        int rot = RandomUtil.randomInt(1, 10);
        g2d.translate(random.nextInt(3), random.nextInt(3));
        g2d.rotate(rot * Math.PI / 180);
        g2d.drawString(randChar, 13 * i, 20);
        g2d.rotate(-rot * Math.PI / 180);
    }

    /**
     * 绘制干扰线
     * @param graphics 获得BufferedImage对象的Graphics对象
     * @author Mr.Zhang
     * @since 2020-04-16
     */
    private static void drawLine(Graphics graphics) {
        //起点(x,y)  偏移量x1、y1
        int x = random.nextInt(WIDTH);
        int y = random.nextInt(HEIGHT);
        int xl = random.nextInt(13);
        int yl = random.nextInt(15);
        graphics.setColor(new Color(random.nextFloat(), random.nextFloat(), random.nextFloat()));
        graphics.drawLine(x, y, x + xl, y + yl);
    }

    /**
     * 生成Base64图片验证码
     * @author Mr.Zhang
     * @since 2020-04-16
     * @return String
     */
    public static Validate getRandomCode() {
        Validate validate = new Validate();

        // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_BGR);
        Graphics graphics = image.getGraphics();// 获得BufferedImage对象的Graphics对象
        graphics.fillRect(0, 0, WIDTH, HEIGHT);//填充矩形
        graphics.setFont(new Font("Times New Roman", Font.PLAIN, 18));//设置字体
        graphics.setColor(getRandColor(110, 133));//设置颜色
        //绘制干扰线
        for (int i = 0; i <= LINE_SIZE; i++) {
            drawLine(graphics);
        }
        //绘制字符
        String randomString = RandomUtils.random(STRING_NUM, new RandomUtils.Alphabet[]{RandomUtils.Alphabet.NUMBERS, RandomUtils.Alphabet.LOWERCASE_LETTERS
                , RandomUtils.Alphabet.UPPERCASE_LETTERS});
        validate.setValue(randomString);
        for (int i = 1; i <= randomString.length(); i++) {
            drawString(graphics, i, String.valueOf(randomString.charAt(i - 1)));
        }
        graphics.dispose();//释放绘图资源
        try (ByteArrayOutputStream bs = new ByteArrayOutputStream()) {
            //将绘制得图片输出到流
            ImageIO.write(image, "png", bs);
            String imgSrc = Base64.byteArrayToBase64(bs.toByteArray());
            validate.setBase64Str(imgSrc);
        } catch (IOException e) {
            validate = null;
        }
        return validate;
    }

    /**
     * 验证码类
     * @author Mr.Zhang
     * @since 2020-04-16
     */
    public static class Validate implements Serializable{

        private static final long serialVersionUID = 1L;
        private String base64Str;        //验证码图片Base64
        private String value;            //验证码值

        public String getBase64Str() {
            return base64Str;
        }
        public void setBase64Str(String base64Str) {
            this.base64Str = base64Str;
        }
        public String getValue() {
            return value;
        }
        public void setValue(String value) {
            this.value = value;
        }
    }

}
